package rlog

import (
	"fmt"
	"gitee.com/zackeus/go-zero/core/logx"
	"os"
	"strings"
)

const (
	LogKeyProducerGroup        = "producerGroup"
	LogKeyConsumerGroup        = "consumerGroup"
	LogKeyTopic                = "topic"
	LogKeyMessageQueue         = "MessageQueue"
	LogKeyAllocateMessageQueue = "AllocateMessageQueue"
	LogKeyUnderlayError        = "underlayError"
	LogKeyBroker               = "broker"
	LogKeyValueChangedFrom     = "changedFrom"
	LogKeyValueChangedTo       = "changeTo"
	LogKeyPullRequest          = "PullRequest"
	LogKeyTimeStamp            = "timestamp"
	LogKeyMessageId            = "msgId"
	LogKeyStoreHost            = "storeHost"
	LogKeyQueueId              = "queueId"
	LogKeyQueueOffset          = "queueOffset"
	LogKeyMessages             = "messages"
)

var defaultLogger struct {
	level uint32
}

func init() {
	defaultLogger = struct{ level uint32 }{level: logx.DebugLevel}
	SetLevel(os.Getenv("ROCKETMQ_GO_LOG_LEVEL"))
}

func format(fields map[string]any) string {
	out := ""
	for k, v := range fields {
		out += fmt.Sprintf("%s=%s  ", k, v)
	}
	return out
}

func SetLevel(level string) {
	if level == "" {
		return
	}

	switch strings.ToLower(level) {
	case "info", "warn":
		defaultLogger.level = logx.InfoLevel
	case "error", "fatal":
		defaultLogger.level = logx.ErrorLevel
	case "debug":
		fallthrough
	default:
		defaultLogger.level = logx.DebugLevel
	}
}

func Debug(msg string, fields map[string]any) {
	if defaultLogger.level > logx.DebugLevel {
		return
	}
	if msg == "" && len(fields) == 0 {
		return
	}
	logx.Debug(fmt.Sprintf("%s     %s", msg, format(fields)))
}

func Info(msg string, fields map[string]any) {
	if msg == "" && len(fields) == 0 {
		return
	}
	if defaultLogger.level > logx.InfoLevel {
		return
	}
	logx.Info(fmt.Sprintf("%s     %s", msg, format(fields)))
}

func Warning(msg string, fields map[string]any) {
	if msg == "" && len(fields) == 0 {
		return
	}
	if defaultLogger.level > logx.InfoLevel {
		return
	}
	logx.Alert(fmt.Sprintf("%s     %s", msg, format(fields)))
}

func Error(msg string, fields map[string]any) {
	if msg == "" && len(fields) == 0 {
		return
	}
	if defaultLogger.level > logx.ErrorLevel {
		return
	}
	logx.Error(fmt.Sprintf("%s     %s", msg, format(fields)))
}

func Fatal(msg string, fields map[string]any) {
	if msg == "" && len(fields) == 0 {
		return
	}
	if defaultLogger.level > logx.ErrorLevel {
		return
	}
	logx.Error(fmt.Sprintf("%s     %s", msg, format(fields)))
}
